/*
@Time : 2019-11-7 上午 9:54
@Author : Gerald
@File : ChatRoomServer.go
@Software: GoLand
*/
package main

import (
	"fmt"
	"io"
	"net"
)

func CheckError(err error, choose string) {
	if err != nil && choose == "exit" {
		panic(err)
	} else if err != nil && choose == "continue" {
		fmt.Println("Bad accept, continue...")
	}
}

func chatCoroutine(conn net.Conn) {
	defer conn.Close()

	// 定义缓存切片，来接收消息
	buf := make([]byte, 1024)

	// 循环接收消息
	for true {
		byteNum, readErr := conn.Read(buf)
		if byteNum == 0 {
			fmt.Println("对端退出！")
			break
		}
		if readErr != nil {
			if readErr == io.EOF {
				fmt.Println("读取完毕！")
				continue
			} else {
				panic(readErr)
			}
		}

		fmt.Println("[", conn.RemoteAddr(), "] : ", string(buf[:byteNum]))
	}
}

func main() {
	// 绑定 ip 和 端口号
	listenSocket, listenErr := net.Listen("tcp", "127.0.0.1:8080")
	CheckError(listenErr, "exit")
	defer listenSocket.Close()

	// 死循环去等待连接
	fmt.Println("Server is waiting...")
	for true {
		// 阻塞等待连接
		conn, acceptErr := listenSocket.Accept()
		CheckError(acceptErr, "continue")

		go chatCoroutine(conn)
	}
}
